package api

import (
	"api-gateway/basic/config"
	__ "api-gateway/basic/proto"
	"api-gateway/handler/request"
	"api-gateway/handler/resp"
	"github.com/gin-gonic/gin"
)

func CreateOrder(c *gin.Context) {
	var req request.CreateOrderReq
	if err := c.ShouldBind(&req); err != nil {
		resp.Error(c, 400, "参数有误", err.Error())
		return
	}

	createOrder, err := config.LearnClient.CreateOrder(c, &__.CreateOrderReq{
		UserId:   int64(c.GetUint("userId")),
		CourseId: req.CourseId,
		Number:   req.Number,
	})
	if err != nil {
		resp.Error(c, 500, "服务端错误", err.Error())
		return
	}

	resp.Success(c, createOrder)
}

func UpdateOrder(c *gin.Context) {
	r := c.Request

	orderSn := r.FormValue("out_trade_no")
	status := r.FormValue("trade_status")

	/*
		WAIT_BUYER_PAY	交易创建，等待买家付款。
		TRADE_CLOSED	未付款交易超时关闭，或支付完成后全额退款。
		TRADE_SUCCESS	交易支付成功。
		TRADE_FINISHED	交易结束，不可退款。
	*/

	if status == "WAIT_BUYER_PAY" {
		config.LearnClient.UpdateOrderStatus(c, &__.UpdateOrderStatusReq{
			OrderSn: orderSn,
			Status:  1,
		})
	} else if status == "TRADE_CLOSED" {
		config.LearnClient.UpdateOrderStatus(c, &__.UpdateOrderStatusReq{
			OrderSn: orderSn,
			Status:  2,
		})
	} else if status == "TRADE_SUCCESS" {
		config.LearnClient.UpdateOrderStatus(c, &__.UpdateOrderStatusReq{
			OrderSn: orderSn,
			Status:  3,
		})
	} else if status == "TRADE_FINISHED" {
		config.LearnClient.UpdateOrderStatus(c, &__.UpdateOrderStatusReq{
			OrderSn: orderSn,
			Status:  4,
		})
	}

	w := c.Writer
	w.Write([]byte("success"))

}

func GetOrderDetail(c *gin.Context) {
	var req request.GetOrderDetailReq
	if err := c.ShouldBind(&req); err != nil {
		resp.Error(c, 400, "参数有误", err.Error())
		return
	}
	orderDetail, err := config.LearnClient.GteOrderDetail(c, &__.GteOrderDetailReq{
		UserId:  int64(c.GetUint("userId")),
		OrderId: req.OrderId,
	})
	if err != nil {
		resp.Error(c, 500, "服务端错误", err.Error())
		return
	}

	resp.Success(c, orderDetail)
}
